<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Robot;
use App\Models\User;
use App\Models\WeixinUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
/**
 * * For the brave souls who get this far: You are the chosen ones,
 * the valiant knights of programming who toil away, without rest,
 * fixing our most awful code. To you, true saviors, kings of men,
 * * I say this: never gonna give you up, never gonna let you down,
 * never gonna run around and desert you. Never gonna make you cry,
 * never gonna say goodbye. Never gonna tell a lie and hurt you. */
/**
 * * 致终于来到这里的勇敢的人：
 * * 你是被上帝选中的人，是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
 * * 你，我们的救世主，人中之龙，我要对你说：永远不要放弃，永远不要对自己失望，永远不要逃走，辜负了自己，
 * * 永远不要哭啼，永远不要说再见，永远不要说谎来伤害自己。
 */
Class RobotController extends Controller
{
    public function intelligentAnswer(Request $request)
    {
        $rules = [
            'keyword'=>'required',
            'token'=>'string'
        ];
        $messages = [
            'keyword.*'=> '要问啥不要空着',
            'token.*'=> '请传递正确令牌',
        ];
        $validator = Validator::make($request->all(), $rules,$messages);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $token = $request->token;

        if($token){//token验证
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if(!$WeixinUser){
                return show(204,"无效token！");
            }else{
                $user= User::find($WeixinUser->user_id);
                if(!$user){
                    return show(204,"用户不存在！");
                }
            }
            $user_id = $user->id;
        }else{//auth验证
            if(!Auth::id()){
                return show(203,'请先登录');
            }
            $user_id = Auth::id();
        }
        $api_key = config('robot.api_key');
        $api_secret = config('robot.api_secret');

        $keyword = $request->keyword;
        $api_url = "http://i.itpk.cn/api.php?question=$keyword&api_key=$api_key&api_secret=$api_secret";
        $data = file_get_contents($api_url);
        $num = Robot::where('user_id',$user_id)->count();
        $num = $num+1;
        $sql = array(
            'user_id'=>$user_id,
            'question'=>$request->keyword,
            'answer'=>$data,
            'num'=>$num
        );
       if(!$data)
       {
           return show('201','empty');
       }
       $res = Robot::create($sql);
       if (!$res){
           return show('201','empty');
       }
       return show('200','ok',$data);
    }
}